import React, { useState, useEffect } from 'react';
import {
    Card,
    Table,
    Button,
    Space,
    Tag,
    Input,
    Select,
    DatePicker,
    Row,
    Col,
    Typography,
    Layout,
    Tooltip,
    message
} from 'antd';
import {
    SearchOutlined,
    EyeOutlined,
    ArrowLeftOutlined,
    ReloadOutlined,
    FilterOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import tradeService from '../../services/tradeService';
import type {
    Trade,
    TradeListParams,
    RestaurantTable,
    User
} from '../../services/tradeService';
import { getFormattedErrorMessage } from '../../services/baseApi';
import './OrdersPage.css';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { Text } = Typography;

interface PaginationState {
    current: number;
    pageSize: number;
    total: number;
}

const OrdersPage: React.FC = () => {
    const navigate = useNavigate();

    // 返回首页
    const handleBack = () => {
        navigate('/dashboard');
    };

    // 订单相关状态
    const [orders, setOrders] = useState<Trade[]>([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState<PaginationState>({
        current: 1,
        pageSize: 20,
        total: 0
    });

    // 搜索和筛选状态
    const [searchParams, setSearchParams] = useState<TradeListParams>({});
    const [filterVisible, setFilterVisible] = useState(false);

    // 加载订单列表
    const loadOrders = async (params?: TradeListParams) => {
        setLoading(true);
        try {
            const queryParams = {
                page: pagination.current,
                pageSize: pagination.pageSize,
                ...searchParams,
                ...params
            };

            const response = await tradeService.getTradeList(queryParams);

            if (response.code === 0 && response.data) {
                setOrders(response.data.list);
                setPagination(prev => ({
                    ...prev,
                    total: response.data!.pagination.total
                }));
            } else {
                message.error(response.message || '获取订单列表失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setLoading(false);
        }
    };

    // 页面初始化加载
    useEffect(() => {
        loadOrders();
    }, [pagination.current, pagination.pageSize]);

    // 搜索处理
    const handleSearch = (value: string) => {
        const newSearchParams = {
            ...searchParams,
            no: value || undefined
        };
        setSearchParams(newSearchParams);
        setPagination(prev => ({ ...prev, current: 1 }));
        loadOrders(newSearchParams);
    };

    // 筛选处理
    const handleFilter = (values: TradeListParams & { dateRange?: [dayjs.Dayjs, dayjs.Dayjs] }) => {
        const newSearchParams = {
            ...searchParams,
            ...values,
            startTime: values.dateRange?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
            endTime: values.dateRange?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
            dateRange: undefined // 移除dateRange字段
        };
        setSearchParams(newSearchParams);
        setPagination(prev => ({ ...prev, current: 1 }));
        loadOrders(newSearchParams);
        setFilterVisible(false);
    };

    // 重置筛选
    const handleResetFilter = () => {
        setSearchParams({});
        setPagination(prev => ({ ...prev, current: 1 }));
        loadOrders({});
    };

    // 查看订单详情
    const handleViewDetail = (order: Trade) => {
        navigate(`/orders/${order.id}`);
    };

    // 翻页处理
    const handlePageChange = (page: number, pageSize: number) => {
        setPagination(prev => ({
            ...prev,
            current: page,
            pageSize: pageSize
        }));
    };

    // 订单状态标签
    const getStatusTag = (status: number) => {
        switch (status) {
            case 0:
                return <Tag>已取消</Tag>;
            case 1:
                return <Tag color="processing">进行中</Tag>;
            case 2:
                return <Tag color="success">已完成</Tag>;
            default:
                return <Tag color="default">未知</Tag>;
        }
    };

    // 支付状态标签
    const getPaymentStatusTag = (paymentStatus: number) => {
        switch (paymentStatus) {
            case 0:
                return <Tag color="error">未支付</Tag>;
            case 1:
                return <Tag color="success">已支付</Tag>;
            default:
                return <Tag color="default">未知</Tag>;
        }
    };

    // 配送类型文本
    const getDeliveryTypeText = (deliveryType: number) => {
        switch (deliveryType) {
            case 1:
                return '堂食';
            case 2:
                return '外卖';
            default:
                return '未知';
        }
    };

    // 订单表格列定义
    const orderColumns: ColumnsType<Trade> = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80,
            fixed: 'left'
        },
        {
            title: '订单号',
            dataIndex: 'no',
            key: 'no',
            width: 200,
            fixed: 'left',
            render: (no: string) => (
                <Text code style={{ fontSize: '12px' }}>{no}</Text>
            )
        },
        {
            title: '餐桌',
            dataIndex: 'restaurantTable',
            key: 'table',
            width: 100,
            render: (table: RestaurantTable) => table?.name || '-'
        },
        {
            title: '用户',
            dataIndex: 'user',
            key: 'user',
            width: 120,
            render: (user: User | null) => user?.username || '游客'
        },
        {
            title: '配送方式',
            dataIndex: 'deliveryType',
            key: 'deliveryType',
            width: 100,
            render: (deliveryType: number) => getDeliveryTypeText(deliveryType)
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status: number) => getStatusTag(status)
        },
        {
            title: '支付状态',
            dataIndex: 'paymentStatus',
            key: 'paymentStatus',
            width: 100,
            render: (paymentStatus: number) => getPaymentStatusTag(paymentStatus)
        },
        {
            title: '原价',
            dataIndex: ['payment', 'originAmount'],
            key: 'originAmount',
            width: 100,
            render: (amount: number) => `¥${amount.toFixed(2)}`
        },
        {
            title: '实付金额',
            dataIndex: ['payment', 'amount'],
            key: 'amount',
            width: 100,
            render: (amount: number) => (
                <Text strong style={{ color: '#52c41a' }}>
                    ¥{amount.toFixed(2)}
                </Text>
            )
        },
        {
            title: '就餐人数',
            dataIndex: 'actualSeats',
            key: 'actualSeats',
            width: 100
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            width: 160,
            render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '支付时间',
            dataIndex: 'payAt',
            key: 'payAt',
            width: 160,
            render: (time: string) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            fixed: 'right',
            render: (_, record) => (
                <Space size="small">
                    <Button
                        type="primary"
                        size="small"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                </Space>
            )
        }
    ];

    // 筛选表单
    const FilterForm = () => (
        <Card title="筛选条件" size="small">
            <Row gutter={16}>
                <Col span={6}>
                    <Select
                        placeholder="订单状态"
                        allowClear
                        style={{ width: '100%' }}
                        value={searchParams.status}
                        onChange={(value) => setSearchParams(prev => ({ ...prev, status: value }))}
                    >
                        <Option value={1}>进行中</Option>
                        <Option value={2}>已完成</Option>
                    </Select>
                </Col>
                <Col span={6}>
                    <Input
                        placeholder="订单号"
                        allowClear
                        value={searchParams.no}
                        onChange={(e) => setSearchParams(prev => ({ ...prev, no: e.target.value }))}
                    />
                </Col>
                <Col span={6}>
                    <Input
                        placeholder="餐桌ID"
                        allowClear
                        type="number"
                        value={searchParams.tableId}
                        onChange={(e) => setSearchParams(prev => ({ ...prev, tableId: e.target.value ? Number(e.target.value) : undefined }))}
                    />
                </Col>
                <Col span={6}>
                    <RangePicker
                        showTime
                        style={{ width: '100%' }}
                        placeholder={['开始时间', '结束时间']}
                        value={searchParams.startTime && searchParams.endTime ? [
                            dayjs(searchParams.startTime),
                            dayjs(searchParams.endTime)
                        ] : undefined}
                        onChange={(dates) => {
                            if (dates) {
                                setSearchParams(prev => ({
                                    ...prev,
                                    startTime: dates[0]?.format('YYYY-MM-DD HH:mm:ss'),
                                    endTime: dates[1]?.format('YYYY-MM-DD HH:mm:ss')
                                }));
                            } else {
                                setSearchParams(prev => ({
                                    ...prev,
                                    startTime: undefined,
                                    endTime: undefined
                                }));
                            }
                        }}
                    />
                </Col>
            </Row>
            <Row style={{ marginTop: 16 }}>
                <Col>
                    <Space>
                        <Button type="primary" onClick={() => handleFilter(searchParams)}>
                            应用筛选
                        </Button>
                        <Button onClick={handleResetFilter}>
                            重置
                        </Button>
                    </Space>
                </Col>
            </Row>
        </Card>
    );

    return (
        <Layout className="orders-layout">
            {/* 统一页头 */}
            <div className="orders-header">
                <div className="header-left">
                    <Button
                        className="back-button"
                        type="text"
                        icon={<ArrowLeftOutlined />}
                        size="large"
                        onClick={handleBack}
                    />
                    <h1 className="page-title">订单管理</h1>
                </div>
                <div className="header-right">
                    <Search
                        placeholder="搜索订单号"
                        allowClear
                        enterButton={<SearchOutlined />}
                        style={{ width: 300 }}
                        onSearch={handleSearch}
                    />
                    <Button
                        icon={<FilterOutlined />}
                        onClick={() => setFilterVisible(!filterVisible)}
                    >
                        筛选
                    </Button>
                    <Tooltip title="刷新数据">
                        <Button
                            icon={<ReloadOutlined />}
                            onClick={() => loadOrders()}
                        >
                            刷新
                        </Button>
                    </Tooltip>
                </div>
            </div>

            {/* 主要内容区域 */}
            <div className="orders-content">
                {/* 筛选表单 */}
                {filterVisible && (
                    <div style={{ marginBottom: 16 }}>
                        <FilterForm />
                    </div>
                )}

                <Card>
                    <Table
                        columns={orderColumns}
                        dataSource={orders}
                        rowKey="id"
                        loading={loading}
                        scroll={{ x: 1500 }}
                        pagination={{
                            current: pagination.current,
                            pageSize: pagination.pageSize,
                            total: pagination.total,
                            showSizeChanger: true,
                            showQuickJumper: true,
                            showTotal: (total) => `共 ${total} 条记录`,
                            onChange: handlePageChange,
                            onShowSizeChange: handlePageChange,
                            pageSizeOptions: ['10', '20', '50', '100']
                        }}
                    />
                </Card>
            </div>
        </Layout>
    );
};

export default OrdersPage; 